package com.zlx.sharelive.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lcw.library.imagepicker.ImagePicker;
import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.AddVideoBean;
import com.zlx.module_base.base_api.res_data.UploadBean;
import com.zlx.module_base.base_api.res_data.VideoChannel;
import com.zlx.module_base.base_api.res_data.VideoChannelBody;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_base.base_util.TimeUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.DecimalInputTextWatcher;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.GlideLoader;
import com.zlx.sharelive.utils.StringUt;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 发布长视频
 */
public class ReleaseVideoAc extends BaseAc {

    @BindView(R.id.ll_money)
    LinearLayout ll_money;
    @BindView(R.id.tv_video_type)
    TextView tv_video_type;
    @BindView(R.id.et_video_title)
    EditText et_video_title;
    @BindView(R.id.et_video_text)
    EditText et_video_text;
    @BindView(R.id.et_video_money)
    EditText et_video_money;
    @BindView(R.id.iv_up_video)
    ImageView iv_up_video;
    @BindView(R.id.bt_video_up)
    Button bt_video_up;
    @BindView(R.id.iv_charge)
    ImageView iv_charge;
    @BindView(R.id.iv_up_cover)
    ImageView iv_up_cover;
    @BindView(R.id.tv_up_cover_text)
    TextView tv_up_cover_text;

    private String title = "";//视频标题
    private String cover = "";//封面 短视频没有
    private String channelId = "";//视频频道id(短视频没有)
    private String context = "";//文案
    private String video = "";//视频
    private String isPaid = "1"; //视频是否收费 1 免费 2 收费 ',
    private String money = "";//视频价格
    private String type = "1";//视频标记(1 长视频 2 短视频)
    private String createTime = "";//创建时间
    private String updateTime = "";//修改时间
    private String filePath = "";
    private String fileCoverPath = "";
    private List<File> fileList = new ArrayList<>();
    private List<VideoChannel.InfoDTO> mList = new ArrayList<>();
    private CommonRecyclerViewAdapter<VideoChannel.InfoDTO> mAdapter;


    @Override
    protected int getLayoutId() {
        return R.layout.ac_release_video;
    }


    @Override
    public void initViews() {
        super.initViews();
        moneyLimit();
    }

    /**
     * 金钱限制
     */
    private void moneyLimit() {
        et_video_money.addTextChangedListener(new DecimalInputTextWatcher(et_video_money, 10, 2));
    }


    @OnClick({R.id.iv_back, R.id.ll_video_type, R.id.iv_up_video, R.id.bt_video_up,
            R.id.ll_charge, R.id.fl_video_cover})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_video_type:
                getVideoChannel();
                break;
            case R.id.iv_up_video:
                ImagePicker.getInstance()
                        .setTitle("选择视频")//设置标题
                        .showCamera(false)//设置是否显示拍照按钮
                        .showImage(false)//设置是否展示图片
                        .showVideo(true)//设置是否展示视频
                        .setSingleType(true)//设置图片视频不能同时选择
                        .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
                        .setImageLoader(new GlideLoader())//设置自定义图片加载器
                        .start(ReleaseVideoAc.this, 1);//REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode      break;
                break;
            case R.id.fl_video_cover:
                //上传封面
                ImagePicker.getInstance()
                        .setTitle("选择封面")//设置标题
                        .showCamera(true)//设置是否显示拍照按钮
                        .showImage(true)//设置是否展示图片
                        .showVideo(false)//设置是否展示视频
                        .setSingleType(false)//设置图片视频不能同时选择
                        .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
                        .setImageLoader(new GlideLoader())//设置自定义图片加载器
                        .start(ReleaseVideoAc.this, 2);//REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode      break;
                break;
            case R.id.bt_video_up:
                if (StringUt.isEmpty(tv_video_type.getText().toString().trim())) {
                    Toast.makeText(this, "请选择频道类目", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (StringUt.isEmpty(et_video_title.getText().toString().trim())) {
                    Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
                    return;
                } else if (StringUt.isEmpty(filePath)) {
                    Toast.makeText(this, "请选择上传的视频", Toast.LENGTH_SHORT).show();
                    return;
                } else if (StringUt.isEmpty(fileCoverPath)) {
                    tv_up_cover_text.setVisibility(View.VISIBLE);
                    Toast.makeText(this, "请选择视频封面", Toast.LENGTH_SHORT).show();
                    return;
                } else if (isPaid.equals("1")) {
                    //不收费 直接上传
                    upload();
                    return;
                } else if (isPaid.equals("2")) {
                    if (StringUt.isEmpty(et_video_money.getText().toString().trim())) {
                        Toast.makeText(this, "请输入收费金额", Toast.LENGTH_SHORT).show();
                        return;
                    } else if (
                            Double.valueOf(et_video_money.getText().toString().trim()) == 0) {
                        Toast.makeText(this, "请输入有效金额", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        //上传
                        upload();
                    }
                    return;
                }
                break;
            case R.id.ll_charge:
                //是否收费
                if (isPaid.equals("2")) {
                    isPaid = "1";
                    iv_charge.setImageResource(R.mipmap.up_off_img);
                    ll_money.setVisibility(View.GONE);
//                    Toast.makeText(this, "不收费", Toast.LENGTH_SHORT).show();
                } else {
                    isPaid = "2";
                    iv_charge.setImageResource(R.mipmap.up_no_img);
                    ll_money.setVisibility(View.VISIBLE);
//                    Toast.makeText(this, "收费", Toast.LENGTH_SHORT).show();
                }
                break;

        }
    }

    /**
     * 上传视频
     */
    private void upload() {
        title = et_video_title.getText().toString().trim();
        context = et_video_text.getText().toString().trim();
        money = et_video_money.getText().toString().trim();
        showLoading();
        fileList.clear();
        fileList.add(new File(filePath));
        ApiUtil.getVideoApi().upload(filesToMultipartBody(fileList)).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<UploadBean>>() {
            @Override
            public void onSuccess(ApiResponse<UploadBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getErrorCode() == 0) {
                            video = data.getData().getInfo().get(0).getUrl();
                            uploadImage();
                        }
                    } else {
                        showSuccess();
                        Toast.makeText(ReleaseVideoAc.this, "服务器异常", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 上传封面
     */
    private void uploadImage() {
        File file = new File(fileCoverPath);
        Log.d("ret", "joker xia    视频封面的地址===" + (null == file));
        List<File> listFile = new ArrayList<>();
        listFile.add(file);
        ApiUtil.getVideoApi().upload(filesToMultipartBody2(listFile)).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<UploadBean>>() {
            @Override
            public void onSuccess(ApiResponse<UploadBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getErrorCode() == 0) {
                            showSuccess();
                            cover = data.getData().getInfo().get(0).getUrl();
                            addFilm();
                        }
                    } else {
                        showSuccess();
                        Toast.makeText(ReleaseVideoAc.this, "服务器异常", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 发布视频
     */
    private void addFilm() {
        VideoChannelBody body = new VideoChannelBody();
        body.setTitle(title);
        body.setCover(cover);
        body.setChannelId(channelId);
        body.setContext(context);
        body.setVideo(video);
        body.setIsPaid(isPaid);
        body.setMoney(money);
        body.setType(type);
        body.setCreateTime(TimeUtil.getCurrentDateTime("yyyy-MM-dd HH-mm-ss"));
        body.setUpdateTime(TimeUtil.getCurrentDateTime("yyyy-MM-dd HH-mm-ss"));
        ApiUtil.getVideoApi().addVideo(SPUtil.getToken(this), body).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<AddVideoBean>>() {
            @Override
            public void onSuccess(ApiResponse<AddVideoBean> data) {
                showSuccess();
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            dialogSuccess();
                        } else {
                            Toast.makeText(ReleaseVideoAc.this, data.getErrorMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        }));
    }

    private void dialogSuccess() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(ReleaseVideoAc.this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(ReleaseVideoAc.this, R.layout.dialog_success, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        TextView tv_continue = view.findViewById(R.id.tv_continue);
        tv_continue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //继续
                dialog.dismiss();
                title = "";
                cover = "";
                channelId = "";
                context = "";
                video = "";
                isPaid = "1";
                money = "";
                type = "1";
                tv_video_type.setText("");
                et_video_title.setText("");
                et_video_text.setText("");
                et_video_money.setText("");
                filePath = "";
                fileCoverPath = "";
                iv_charge.setImageResource(R.mipmap.up_off_img);
                iv_up_video.setImageResource(R.mipmap.up_video_img);
                iv_up_cover.setImageResource(0);
                tv_up_cover_text.setVisibility(View.VISIBLE);
                ll_money.setVisibility(View.GONE);
            }
        });

        TextView tv_black = view.findViewById(R.id.tv_black);
        tv_black.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回首页
                dialog.dismiss();
                finish();
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 获取频道列表
     */
    private void getVideoChannel() {
        ApiUtil.getVideoApi().getVideoChannel(SPUtil.getToken(ReleaseVideoAc.this)).observe(
                this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<VideoChannel>>() {
                    @Override
                    public void onSuccess(ApiResponse<VideoChannel> data) {
                        mList.clear();
                        mList.addAll(data.getData().getInfo());
                        if (mList.size() > 0) {
                            for (int i = 0; i < mList.size(); i++) {
                                if (i == 0) {
                                    mList.get(i).setCheck(true);
                                } else {
                                    mList.get(i).setCheck(false);
                                }
                            }
                        }
                        dialog();
                    }

                    @Override
                    public void onFail(String msg) {
                        super.onFail(msg);

                    }
                }));
    }

    /**
     * 频道列表展示
     */
    private void dialog() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_channel_list, null);
        dialog.setContentView(view);

        RecyclerView dialog_recycler = view.findViewById(R.id.dialog_recycler);

        dialog_recycler.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new CommonRecyclerViewAdapter<VideoChannel.InfoDTO>(this, mList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, VideoChannel.InfoDTO entity, int position) {
                holder.setText(R.id.tv_text, entity.getName());
                TextView tv_text = holder.getView(R.id.tv_text);
                if (entity.isCheck() == true) {
                    tv_text.setTextColor(getResources().getColor(R.color.black));
                } else {
                    tv_text.setTextColor(getResources().getColor(R.color.martini));
                }
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_channel_list;
            }
        };

        dialog_recycler.setAdapter(mAdapter);

        ImageView iv_close = view.findViewById(R.id.iv_close);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        TextView tv_complete = view.findViewById(R.id.tv_complete);

        tv_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).isCheck() == true) {
                        tv_video_type.setText(mList.get(i).getName());
                        channelId = mList.get(i).getId();
                    }
                }
                dialog.dismiss();
            }
        });

        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                for (int i = 0; i < mList.size(); i++) {
                    if (position == i) {
                        mList.get(position).setCheck(true);
                    } else {
                        mList.get(i).setCheck(false);
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
            filePath = imagePaths.get(0);
            Bitmap bitmap = createVideoThumbnail(imagePaths.get(0));
            iv_up_video.setImageBitmap(bitmap);
            Log.d("ret", "joker   视频地址===" + imagePaths);
        } else if (requestCode == 2 && resultCode == RESULT_OK) {
            //封面
            List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
            fileCoverPath = imagePaths.get(0);
            tv_up_cover_text.setVisibility(View.GONE);
//            Bitmap bitmap = createVideoThumbnail(imagePaths.get(0));
//            iv_up_cover.setImageBitmap(bitmap);
            GlideImgManager.glideLoaderFile(this, new File(fileCoverPath), iv_up_cover, 1);
            Log.d("ret", "joker   封面===" + imagePaths);
        }
    }

    /**
     * 获取视频第一帧图片
     */
    private Bitmap createVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        return bitmap;
    }

    //bitmap转file
//    public File saveBitmapFile(Bitmap bitmap) {
//        Calendar Cld = Calendar.getInstance();
//        long timeInMillis = Cld.getTimeInMillis();
//        String timeName = String.valueOf(timeInMillis / 1000);
//        Log.d("ret", "joker xia 存图片的地址=" + getSystemFilePath(ReleaseVideoAc.this) + "/sdcard/pic/" + timeName + ".jpg");
//        File file = new File(getSystemFilePath(ReleaseVideoAc.this) + timeName + ".jpg");//将要保存图片的路径
//        try {
//            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
//            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
//            bos.flush();
//            bos.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return file;
//    }
    public static MultipartBody filesToMultipartBody(List<File> files) {
        MultipartBody.Builder builder = new MultipartBody.Builder();

        for (File file : files) {
            // TODO: 16-4-2  这里为了简单起见，没有判断file的类型
            RequestBody requestBody = RequestBody.create(MediaType.parse("video/mp4"), file);
            builder.addFormDataPart("file", file.getName(), requestBody);
        }

        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

    public static MultipartBody filesToMultipartBody2(List<File> files) {
        MultipartBody.Builder builder = new MultipartBody.Builder();

        for (File file : files) {
            // TODO: 16-4-2  这里为了简单起见，没有判断file的类型
            RequestBody requestBody = RequestBody.create(MediaType.parse("video/jpg"), file);
            builder.addFormDataPart("file", file.getName(), requestBody);
        }

        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }


    /**
     * 获取app 路径
     *
     * @param context
     * @return
     */
    private static String getSystemFilePath(Context context) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
//            cachePath = context.getExternalCacheDir().getPath();//也可以这么写，只是返回的路径不一样，具体打log看
        } else {
            cachePath = context.getFilesDir().getAbsolutePath();
//            cachePath = context.getCacheDir().getPath();//也可以这么写，只是返回的路径不一样，具体打log看
        }
        return cachePath;
    }

}
